package com.example.universitylibraryback.service;

import org.kie.api.KieServices;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.Message;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DynamicRuleService {
    
    @Autowired
    private KieServices kieServices;
    
    @Autowired
    private KieContainer kieContainer;
    
    /**
     * 动态添加规则
     */
    public void addRule(String ruleContent, String ruleName) {
        // 每次使用时动态创建KieFileSystem（临时对象）
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        
        // 使用正确的资源路径格式和参数顺序
        String rulePath = "rules/" + ruleName + ".drl";
        kieFileSystem.write(rulePath, ResourceFactory.newByteArrayResource(ruleContent.getBytes()));
        
        // 使用kieServices创建KieBuilder
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        
        if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
            throw new RuntimeException("规则语法错误: " + kieBuilder.getResults().toString());
        }
        
        // 获取KieRepository并通知KieContainer更新
        KieRepository kieRepository = kieServices.getRepository();
        kieContainer.updateToVersion(kieRepository.getDefaultReleaseId());
    }
}